package org.apaydin.widget;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class BitmapUtils {

    public static Bitmap getImageBitmap(String url, int width, int height) {
        Bitmap bitmap = getImageBitmap(url);
        return Bitmap.createScaledBitmap(bitmap, width, height, false);
    }

    public static Bitmap getImageBitmap(String url) {
        try {
            Bitmap bm = null;
            URL aURL = new URL(url);
            URLConnection conn = aURL.openConnection();
            conn.connect();
            InputStream is = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            bm = BitmapFactory.decodeStream(bis);
            bis.close();
            is.close();
            return bm;
        } catch (IOException e) {
            Log.e(url, "Error getting bitmap", e);
        }
        return null;
    }


    public static Bitmap scaleImage(Bitmap bitmap, int maxWidth, int maxHeight) {
        float oran = (float) maxWidth / bitmap.getWidth();
        if(oran*bitmap.getHeight() > maxHeight){
            oran = (float) maxHeight / bitmap.getHeight();
        }
        return Bitmap.createScaledBitmap(bitmap, (int) (oran * bitmap.getWidth()), (int) (oran * bitmap.getHeight()), false);
    }
}
